package com.jxwifi.cloud.quickclean.map;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.TextOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.basicactivity.BasicActivity;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.adapter.mMapSearchAdapter;
import com.jxwifi.cloud.quickclean.app.ClientBasicActivity;
import com.jxwifi.cloud.quickclean.app.LocationGaoDe;
import com.jxwifi.cloud.quickclean.bean.PoiItemBean;
import com.jxwifi.cloud.quickclean.utils.KeyboardUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ListUtils;

public class MapActivity extends ClientBasicActivity implements AMapLocationListener,AMap.OnCameraChangeListener,PoiSearch.OnPoiSearchListener
        ,SwipeRefreshLayout.OnRefreshListener,KeyboardUtil.OnSoftKeyboardChangeListener{

    private String TAG = this.getClass().getSimpleName();
    @Bind(R.id.mp_map_work)
    MapView mMapView;
    //初始化地图控制器对象
    AMap aMap;
    @Bind(R.id.srl_map_search_list)
    SwipeRefreshLayout mSrlMapSearchList;
    @Bind(R.id.rv_map_search_list)
    RecyclerView mRvMapSearchList;
    @Bind(R.id.tv_map_search_city)
    TextView mTvMapSearchCity;
    @Bind(R.id.et_map_search_address)
    EditText mEtMapSearchAdaaress;
    @Bind(R.id.lin_mp_map_work)
    LinearLayout mLinMpMapWork;

    private mMapSearchAdapter mAdapter;
    private int mPageIndex = 1;//页数
    private int mLastVisibleItemIndex;//用于记录滑动监听中Item的位置
    private LinearLayoutManager mLayoutManager;
    //表示是否可以上拉刷新.因为APP中上拉刷新没有添加动画效果，在数据加载的时候，会多次请求上拉刷新的判断，导致数据没加载完成前，再次的执行了数据请求方法
    //数据页数是根据请求的次数叠加的，就会出现数据为空的情况，特加这个字段做判断
    private boolean mIsrefresh = true;

    private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener;

    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private Marker locationMarker;
    private PoiSearch.Query query;// Poi查询条件类
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch poiSearch;// POI搜索
    private PoiResult poiResult; // poi返回的结果
    private LatLonPoint mlatLonPoint;//每次地图移动后得到的坐标信息
    private boolean mIsvisible;//根据软键盘的显示来调整地图移动的请求

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_search);
        ButterKnife.bind(this);
        openEventBus();
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
            aMap.setOnCameraChangeListener(this);// 对amap添加移动地图事件监听器
        }
        mOnGlobalLayoutListener = KeyboardUtil.observeSoftKeyboard(this, this);

        initView();
    }

    public void initView() {
        mLocationClient = new AMapLocationClient(getApplicationContext());////初始化定位
        mLocationOption = new AMapLocationClientOption();////初始化AMapLocationClientOption对象
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);////设置定位模式为高精度模式。
        mLocationClient.setLocationListener(this);////设置定位回调监听
        mLocationOption.setOnceLocation(true);////获取一次定位结果
        mLocationOption.setNeedAddress(true);////设置是否返回地址信息（默认返回地址信息）
        mLocationClient.setLocationOption(mLocationOption);////给定位客户端对象设置定位参数
        mLocationClient.startLocation();////启动定位

        mTvMapSearchCity.setText(LocationGaoDe.getCity());

        mRvMapSearchList.setLayoutManager(mLayoutManager = new LinearLayoutManager(mBaseContext));
        mRvMapSearchList.setAdapter(mAdapter = new mMapSearchAdapter(mBaseContext));
        mSrlMapSearchList.setColorSchemeColors(0xfffe8026);
        mSrlMapSearchList.setOnRefreshListener(this);
        /**
         * 上拉刷新监听方法（在RecyclerView控件中实现这个方法）
         */
        mRvMapSearchList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLastVisibleItemIndex + 1 == mAdapter.getItemCount() ) {
                    mIsrefresh = false;
                    onLoadMore();
                }
            }

            /**
             * 监听滑动中的时候Item的位置
             * @param recyclerView
             * @param dx
             * @param dy
             */
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mLastVisibleItemIndex = mLayoutManager.findLastVisibleItemPosition();
            }
        });

        mEtMapSearchAdaaress.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)) {
                    mPageIndex=1;
                    // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
                    query=new  PoiSearch.Query(s.toString(), "", LocationGaoDe.getCity());
                    query.setPageSize(10);// 设置每页最多返回多少条poiitem
                    query.setPageNum(mPageIndex);// 设置查第一页
                    poiSearch = new PoiSearch(mBaseContext, query);
                    poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                        @Override
                        public void onPoiSearched(PoiResult result, int i) {
                            if (result != null && result.getQuery() != null) {
                                List<PoiItemBean> mBean=new ArrayList<PoiItemBean>();
                                poiResult = result;
                                // 取得搜索到的poiitems有多少页
                                mSrlMapSearchList.setRefreshing(false);
                                List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                                if (ListUtils.isEmpty(poiItems)||poiItems==null){ //当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                                    //搜索无数据的时候可以做下优化，待开发
                                }else{
                                    for (int j=0;j<poiItems.size();j++){
                                        PoiItemBean mpoi=new PoiItemBean();
                                        mpoi.setLatitude(poiItems.get(j).getLatLonPoint().getLatitude());
                                        mpoi.setLongitude(poiItems.get(j).getLatLonPoint().getLongitude());
                                            mpoi.setSnippet(poiItems.get(j).getSnippet()+""+poiItems.get(j).getTitle());
                                        mpoi.setTitle(poiItems.get(j).getTitle());
                                        //getAdCode()返回的是城市编码，而CityCode返回的是邮政编码，这里如果需要获取市的编码需要改下后2位的值，改为00
                                        StringBuilder citycode = new StringBuilder(poiItems.get(j).getAdCode());
                                        //Log.i(TAG,"citycode = "+citycode);
                                        citycode.replace(4,citycode.length(),"00");
                                        mpoi.setCitycode(citycode.toString());
                                        mBean.add(mpoi);
                                    }
                                    if (mPageIndex==1){
                                        mAdapter.refresh(mBean);
                                        Log.w("oushuhua","搜索数据加载，再次定位");
                                        LatLng latLng = new LatLng(poiItems.get(0).getLatLonPoint().getLatitude(),
                                                poiItems.get(0).getLatLonPoint().getLongitude());
                                        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                                    }else{
                                        mAdapter.addData(mBean);
                                    }
                                }

                            }
                        }

                        @Override
                        public void onPoiItemSearched(PoiItem poiItem, int i) {

                        }
                    });
                    poiSearch.searchPOIAsyn();
                }else{
                    Log.w("oushuhua","搜索为空，定位上次得到的坐标");
                    onRefresh();
                }
            }
        });
    }

    @OnClick({R.id.rel_img_back_pressed,R.id.tv_again_location})
    void clickCK(View v){
        switch (v.getId()){
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
            case R.id.tv_again_location:
                LatLng latLng = new LatLng(LocationGaoDe.getLatitude(),LocationGaoDe.getLongitude());
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                mlatLonPoint=new LatLonPoint(LocationGaoDe.getLatitude(),LocationGaoDe.getLongitude());
                mEtMapSearchAdaaress.setText("");
                onRefresh();
                break;
        }
    }

    @Override
    public void onSoftKeyBoardChange(int softKeyboardHeight, boolean visible) {
        mIsvisible=visible;
        if (visible){
            mLinMpMapWork.setVisibility(View.GONE);
        }else{
            mLinMpMapWork.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onRefresh() {
        mPageIndex = 1;
        searchNearby();
    }

    private void onLoadMore() {
        mPageIndex++;
        mSrlMapSearchList.setRefreshing(true);
        searchNearby();
    }



    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //可在其中解析amapLocation获取相应内容。
                LatLng latLng = new LatLng(aMapLocation.getLatitude(),
                        aMapLocation.getLongitude());//取出经纬度
                //添加Marker显示定位位置
                if (locationMarker == null) {
                    //如果是空的添加一个新的,icon方法就是设置定位图标，可以自定义
                    Bitmap bitmap = BitmapFactory.decodeResource(mBaseContext.getResources(), R.mipmap.icon_location_images);
                    if (aMap==null){
                        aMap = mMapView.getMap();
                    }
                    locationMarker = aMap.addMarker(new MarkerOptions()
                            .position(latLng).draggable(true).setFlat(true).icon(BitmapDescriptorFactory.fromBitmap(bitmap)));
                    locationMarker.showInfoWindow();//主动显示indowindow
                    aMap.addText(new TextOptions().position(latLng).text(aMapLocation.getAddress()));
                    //固定标签在屏幕中央
                    locationMarker.setPositionByPixels(mMapView.getWidth() / 2, mMapView.getHeight() / 2);
                } else {
                    //已经添加过了，修改位置即可
                    locationMarker.setPosition(latLng);
                }
                //然后可以移动到定位点,使用animateCamera就有动画效果
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));//参数提示:1.经纬度 2.缩放级别
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:" + aMapLocation.getErrorCode() + ", errInfo:" + aMapLocation.getErrorInfo());
            }
        }
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {


    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        LatLng mFinalChoosePosition = cameraPosition.target;
        mlatLonPoint=new LatLonPoint(mFinalChoosePosition.latitude,mFinalChoosePosition.longitude);
        if (!mIsvisible){
            mPageIndex=1;
            searchNearby();
        }
    }


    public void searchNearby(){
        query=new  PoiSearch.Query("", "", "");
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(mPageIndex);// 设置查第一页
        Log.w("oushuhua","mPageIndex="+mPageIndex);
        poiSearch = new PoiSearch(this, query);
        poiSearch.setBound(new PoiSearch.SearchBound(mlatLonPoint, 5000, true));//
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onPoiSearched(PoiResult result, int i) {
        if (result != null && result.getQuery() != null) {
            List<PoiItemBean> mBean=new ArrayList<PoiItemBean>();
            poiResult = result;
            // 取得搜索到的poiitems有多少页
            mSrlMapSearchList.setRefreshing(false);
            List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
            //Log.i(TAG,"onPoiSearched ==> poiResult.getPois() = "+ JSON.toJSONString(poiResult.getPois()));
            if (!ListUtils.isEmpty(poiItems)){
                mTvMapSearchCity.setText(poiItems.get(0).getCityName());
            }

            for (int j=0;j<poiItems.size();j++){
                PoiItemBean mpoi=new PoiItemBean();
                mpoi.setLatitude(poiItems.get(j).getLatLonPoint().getLatitude());
                mpoi.setLongitude(poiItems.get(j).getLatLonPoint().getLongitude());
                mpoi.setSnippet(poiItems.get(j).getSnippet());
                //Log.i(TAG,"onPoiSearched ==> getSnippet = "+poiItems.get(j).getSnippet());
                mpoi.setTitle(poiItems.get(j).getTitle());
                mpoi.setCitycode(poiItems.get(j).getAdCode());
                mBean.add(mpoi);
            }
            if (mPageIndex==1){
                mAdapter.refresh(mBean);
            }else{
                mAdapter.addData(mBean);
            }

        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    protected void onPause() {
        super.onPause();
        // 暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 重新绘制加载地图
        mMapView.onResume();
        if (locationMarker!=null){
            locationMarker.remove();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 销毁地图
        mMapView.onDestroy();
        if (locationMarker!=null){
            locationMarker.remove();
        }
    }
}
